package cn.com.codes.iteration.blh;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

import cn.com.codes.bugManager.blh.BugManagerBlh;
import cn.com.codes.caseManager.blh.CaseManagerBlh;
import cn.com.codes.common.SecurityContextHolderHelp;
import cn.com.codes.common.dto.PageModel;
import cn.com.codes.common.util.StringUtils;
import cn.com.codes.framework.app.blh.BusinessBlh;
import cn.com.codes.framework.app.view.View;
import cn.com.codes.framework.common.JsonUtil;
import cn.com.codes.framework.exception.BaseException;
import cn.com.codes.framework.security.VisitUser;
import cn.com.codes.framework.security.filter.SecurityContextHolder;
import cn.com.codes.framework.transmission.events.BusiRequestEvent;
import cn.com.codes.iteration.dto.IterationDto;
import cn.com.codes.iteration.dto.IterationVo;
import cn.com.codes.iteration.service.IterationService;
import cn.com.codes.object.ApiTestScene;
import cn.com.codes.object.BugBaseInfo;
import cn.com.codes.object.IterationBugReal;
import cn.com.codes.object.IterationInterfaceReal;
import cn.com.codes.object.IterationList;
import cn.com.codes.object.IterationOperationHistory;
import cn.com.codes.object.IterationTaskReal;
import cn.com.codes.object.IterationTestcasepackageReal;
import cn.com.codes.object.OtherMission;
import cn.com.codes.object.TestCasePackage;
import cn.com.codes.object.User;
import cn.com.codes.object.UserOtherMission;
import cn.com.codes.object.UserTestCasePkg;
import cn.com.codes.otherMission.service.OtherMissionService;
import cn.com.codes.outlineManager.service.OutLineManagerService;


public class IterationBlh extends BusinessBlh {
	
	private BugManagerBlh bugManagerBlh;
	private IterationService iterationService;
	private OtherMissionService otherMissionService;
	private OutLineManagerService outLineService;
	private CaseManagerBlh caseManagerBlh;

	private static Logger logger = Logger.getLogger(IterationBlh.class);
	
	public View iterationList(BusiRequestEvent req){
		return super.getView();
	}
	
	/** 
	* 方法名:          iterationDataListLoad
	* 方法功能描述:      展示列表信息
	* @param:          
	* @return:        
	* @Author:          
	* @Create Date:   2018年8月20日 下午4:09:13
	*/
	@SuppressWarnings("unchecked")
	public View iterationDataListLoad(BusiRequestEvent req){
		IterationDto dto = super.getDto(IterationDto.class, req);

		Integer isAdmin = SecurityContextHolder.getContext().getVisit().getUserInfo(VisitUser.class).getIsAdmin();
		PageModel pageModel = new PageModel(); 
		if(null != dto.getIterationList()) {
			if((dto.getIterationList().getIterationBagName()!=null&&"%".equals(dto.getIterationList().getIterationBagName().trim()))||(dto.getIterationList().getCreatePerson()!=null&&"%".equals(dto.getIterationList().getCreatePerson().trim()))) {
				pageModel.setRows(new ArrayList<IterationVo>());
				pageModel.setTotal(0);
				super.writeResult(JsonUtil.toJson(pageModel));
				return super.globalAjax();
			}
		}
		if(isAdmin==1||isAdmin==2){
			//hql查询
			this.buildIterationDataListSql(dto);
			pageModel.setQueryHql(dto.getHql());
			pageModel.setPageNo(dto.getPageNo());
			pageModel.setPageSize(dto.getPageSize());
			pageModel.setHqlParamMap(dto.getHqlParamMaps());
			iterationService.getJdbcTemplateWrapper().fillPageModelData(pageModel,IterationList.class, "iteration_id");
			List<IterationList> iterLists = (List<IterationList>)pageModel.getRows();

		}else {
			String useId = SecurityContextHolder.getContext().getVisit().getUserInfo(VisitUser.class).getId();
			dto.getIterationList().setUserId(useId);
			List<IterationVo> vos = new ArrayList<IterationVo>();
			if(StringUtils.isNullOrEmpty(dto.getIterationList().getCreatePerson()) && StringUtils.isNullOrEmpty(dto.getIterationList().getIterationBagName())
					&& StringUtils.isNullOrEmpty(dto.getIterationList().getAssociationProject()) && StringUtils.isNullOrEmpty(dto.getIterationList().getIterationId())){
				vos = iterationService.differentPersonWatchIterationDataInfo(dto);
			}else{
				vos = iterationService.differentPersonWatchIterationDataInfoWithParams(dto);
			}
			
			if(vos == null){
				pageModel.setRows(new ArrayList<IterationVo>());
				pageModel.setTotal(0);
			}else{
				pageModel.setRows(vos);
				pageModel.setTotal(dto.getTotal());
			}
			
		}
		
		super.writeResult(JsonUtil.toJson(pageModel));
		return super.globalAjax();
	}



	/** 
	* 方法名:          buildIterationDataListHql
	* 方法功能描述:      拼接hql
	* @param:         
	* @return:        
	* @Author:          
	* @Create Date:   2018年8月20日 下午4:08:59
	*/
	private void buildIterationDataListSql(IterationDto dto) {
			StringBuffer sql = new StringBuffer();
			Map<String,Object> hashMap = new HashMap<String,Object>();
			IterationList iterationList = dto.getIterationList();
			StringBuffer sql2 = new StringBuffer();
			sql.append(" select it.* from t_iteration_list  it  join t_single_test_task st on it.task_id= st.taskid   and  st.status_flg<>4 where 1=1  ");
			sql2.append(" select it.*  from t_iteration_list  it  where  (it.task_id is null or it.task_id='')  ");
			if(null != iterationList){
				//根据迭代包名称
				if(!StringUtils.isNullOrEmpty(iterationList.getIterationBagName())){
					sql.append("and it.iteration_bag_name like :iterationBagName ");
					sql2.append("and it.iteration_bag_name like :iterationBagName ");
					hashMap.put("iterationBagName", "%"+iterationList.getIterationBagName()+"%");
				}
				
				//根据关联项目
				if(!StringUtils.isNullOrEmpty(iterationList.getAssociationProject())){
					sql.append("and it.association_project like :associationProject ");
					sql2.append("and it.association_project like :associationProject ");
					hashMap.put("associationProject", "%"+iterationList.getAssociationProject()+"%");
				}
				
				//根据创建人
				if(!StringUtils.isNullOrEmpty(iterationList.getCreatePerson())){
					sql.append("and it.create_person like :createPerson ");
					sql2.append("and it.create_person like :createPerson ");
					hashMap.put("createPerson", "%"+iterationList.getCreatePerson()+"%");
				}
				
				
				//根据status,0未删除状态，1删除
				if(!StringUtils.isNullOrEmpty(iterationList.getStatus())){
					sql.append("and it.status =:status ");
					sql2.append("and it.status =:status ");
					hashMap.put("status", "0");
				}
				
				//根据迭代主键id
				if(!StringUtils.isNullOrEmpty(iterationList.getIterationId())){
					sql.append("and it.iteration_id =:iterationId ");
					sql2.append("and it.iteration_id =:iterationId ");
					hashMap.put("iterationId",iterationList.getIterationId());
				}
				
				//根据taskid
				if(!StringUtils.isNullOrEmpty(iterationList.getTaskId())){
					sql.append("and it.task_id =:taskId ");
					hashMap.put("taskId", iterationList.getTaskId());
				}
				
				//根据时间
				if(iterationList.getCreateTime() != null&&!"".equals(iterationList.getCreateTime())){
					SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					Date createTime = iterationList.getCreateTime();
					String timeFormat = dateFormat.format(createTime);
					sql.append("and it.create_time =:createTime ");
					hashMap.put("createTime",timeFormat);
				}
			}
			
			String exeSql = "select  base.* from ("+sql.toString()+
				     "  union all " + sql2.toString() +") base order by base.update_time ,base.create_time desc";
			dto.setHql(exeSql);
			if(logger.isInfoEnabled()){
				logger.info(exeSql);
			}
			dto.setHqlParamMaps(hashMap);
			
	}


	/** 
	* 方法名:          saveOrUpdate
	* 方法功能描述:      增加和修改方法
	* @param:         
	* @return:        
	* @Author:          
	* @Create Date:   2018年8月16日 下午4:32:10
	*/
	public View saveOrUpdateIteration(BusiRequestEvent req){
		IterationDto dto = super.getDto(IterationDto.class, req);
		if("".equals(dto.getIterationList().getIterationId())){
			dto.getIterationList().setStatus("0");//0:未更改关联，1：更改关联，未删除数据
			dto.getIterationList().setIterationStatus("3");//0、进行中，1、完成，2、结束，3、准备，5、暂停，6、终止
			dto.getIterationList().setCreateTime(new Date());
			iterationService.addIterationData(dto);
		}else{
			iterationService.updateIterationData(dto);
		}
		super.writeResult("success");
		return super.globalAjax();
	}
	
	/** 
	* 方法名:          saveTestCasePackage
	* 方法功能描述:      保存迭代与用例的关联信息
	* @param:         
	* @return:        
	* @Author:          
	* @Create Date:   2018年8月29日 下午3:09:17
	*/
	public View saveTestCasePackage(BusiRequestEvent req){
		IterationDto dto = super.getDto(IterationDto.class, req);
		if(!StringUtils.isNullOrEmpty(dto.getTestCaseP())){//testcasepackage关联,t_iteration_testcasepackage_real
			String[] testcase = dto.getTestCaseP().split(",");
			List<IterationTestcasepackageReal> iterationTestcaseList = new ArrayList<IterationTestcasepackageReal>();
			for (int i = 0; i < testcase.length; i++) {
				IterationTestcasepackageReal iterationTestcase = new IterationTestcasepackageReal();
				iterationTestcase.setIterationId(dto.getIterationList().getIterationId());
				iterationTestcase.setPackageId(testcase[i]);
				iterationTestcaseList.add(iterationTestcase);
			}
			iterationService.batchSaveTestCasePackage(iterationTestcaseList);
		}
		super.writeResult("success");
		return super.globalAjax();
	}
	
	/** 
	* 方法名:          saveTaskReal
	* 方法功能描述:      保存迭代与任务的信息
	* @param:         
	* @return:        
	* @Author:          
	* @Create Date:   2018年8月30日 下午2:22:21
	*/
	public View saveTaskReal(BusiRequestEvent req){
		IterationDto dto = super.getDto(IterationDto.class, req);
		if(!StringUtils.isNullOrEmpty(dto.getOtherMissionS())){//task关联,t_iteration_task_real
			String[] otherMissi = dto.getOtherMissionS().split(",");
			List<IterationTaskReal> IterationTaskRealList = new ArrayList<IterationTaskReal>();
			for (int i = 0; i < otherMissi.length; i++) {
				 IterationTaskReal iterationTaskReal = new IterationTaskReal();
				 iterationTaskReal.setIterationId(dto.getIterationList().getIterationId());
				 iterationTaskReal.setMissionId(otherMissi[i]);
				 IterationTaskRealList.add(iterationTaskReal);
			}
			iterationService.batchSaveIteraTask(IterationTaskRealList);
		}
		super.writeResult("success");
		return super.globalAjax();
	}
	
	/** 
	* 方法名:          saveBugReal
	* 方法功能描述:      保存迭代与bug的信息
	* @param:         
	* @return:        
	* @Author:          
	* @Create Date:   2018年8月30日 下午4:58:16
	*/
	public View saveBugReal(BusiRequestEvent req){
		IterationDto dto = super.getDto(IterationDto.class, req);
		if(!StringUtils.isNullOrEmpty(dto.getBugCardId())){//task关联,t_iteration_bug_real
			String[] bugCards = dto.getBugCardId().split(",");
			List<IterationBugReal> iterationBugReals = new ArrayList<IterationBugReal>();
			for (int i = 0; i < bugCards.length; i++) {
				 IterationBugReal iterationBugReal = new IterationBugReal();
				 iterationBugReal.setIterationId(dto.getIterationList().getIterationId());
				 iterationBugReal.setBugCardId(bugCards[i]);
				 iterationBugReals.add(iterationBugReal);
			}
			iterationService.batchSaveIteraBug(iterationBugReals);
		}
		
		super.writeResult("success");
		return super.globalAjax();
	}
	
	/** 
	* 方法名:          saveInterfaceReal
	* 方法功能描述:      保存迭代与接口的信息
	* @param:         
	* @return:        
	* @Author:          
	* @Create Date:   2018年8月30日 下午4:58:16
	*/
	public View saveInterfaceReal(BusiRequestEvent req){
		IterationDto dto = super.getDto(IterationDto.class, req);
		if(!StringUtils.isNullOrEmpty(dto.getInterfaceId())){//task关联,t_iteration_interface_real
			String[] interfaceIds = dto.getInterfaceId().split(",");
			List<IterationInterfaceReal> iterationInterfaceReals = new ArrayList<IterationInterfaceReal>();
			for (int i = 0; i < interfaceIds.length; i++) {
				IterationInterfaceReal iterationInterfaceReal = new IterationInterfaceReal();
				iterationInterfaceReal.setIterationId(dto.getIterationList().getIterationId());
				iterationInterfaceReal.setInterfaceId(interfaceIds[i]);
				iterationInterfaceReals.add(iterationInterfaceReal);
			}
			iterationService.batchSaveIteraInterface(iterationInterfaceReals);
		}
		
		super.writeResult("success");
		return super.globalAjax();
	}
	
	
	/** 
	* 方法名:          findUpdateIterationInfo
	* 方法功能描述:      查询需要修改的信息
	* @param:         
	* @return:        
	* @Author:          
	* @Create Date:   2018年8月21日 下午1:35:44
	*/
	public View findUpdateIterationInfo(BusiRequestEvent req){
		IterationDto dto = super.getDto(IterationDto.class, req);
		List<IterationList> iterList = iterationService.findByProperties(IterationList.class, 
									     new String[]{"iterationId"},
											new Object[]{dto.getIterationList().getIterationId()});
		if(iterList.size() > 0){
			dto.setIterationLists(iterList);
		}else {
			dto.setIterationLists(null);
		}
		iterationService.getBugTaskTestcaseInfo(dto);
		
		super.writeResult(JsonUtil.toJson(dto));
		return super.globalAjax();
	}
	
	/** 
	* 方法名:          deleteIterationInfo
	* 方法功能描述:      删除迭代记录
	* @param:         
	* @return:        
	* @Author:          
	* @Create Date:   2018年8月22日 下午1:57:27
	*/
	public View deleteIterationInfo(BusiRequestEvent req){
		IterationDto dto = super.getDto(IterationDto.class, req);
		iterationService.deleteIterationAboutInfo(dto);
		super.writeResult("success");
		return super.globalAjax();
	}
	
	/** 
	* 方法名:          searchBugDetail
	* 方法功能描述:     查询关联的bug
	* @param:         
	* @return:        
	* @Author:          
	* @Create Date:   2018年8月29日 下午5:30:19
	*/
	@SuppressWarnings("unchecked")
	public View searchBugDetail(BusiRequestEvent req){
		IterationDto dto = super.getDto(IterationDto.class, req);
		if(null==dto.getPageModel()){
			dto.setPageModel(new PageModel());
		}
		
		iterationService.bugDetail(dto);
		List<BugBaseInfo> bugBaseInfos = new ArrayList<BugBaseInfo>();
		List<Map<String, Object>> infos = (List<Map<String, Object>>) dto.getPageModel().getRows();
		PageModel pageModel = new PageModel();
		String taskIdTemp = null;
		if(infos!=null){
			if(infos.size()>0){
				for (int i = 0; i < infos.size(); i++) {
					BugBaseInfo bugBaseInfo = new BugBaseInfo();
					String taskId = (String) infos.get(i).get("taskId");
					if(taskIdTemp==null) {
						taskIdTemp = taskId ; // 不要删要不后续处理测试包会有BUG 
					}
					String bugDesc = (String) infos.get(i).get("bugDesc");
					Long bugId = (Long) infos.get(i).get("bugId");
					Long bugTypeId = (Long) infos.get(i).get("bugTypeId");
					Integer currStateId = (Integer) infos.get(i).get("currStateId");
					Long bugGradeId = (Long) infos.get(i).get("bugGradeId");
					Long geneCauseId = (Long) infos.get(i).get("geneCauseId");
					Long priId = (Long) infos.get(i).get("priId");
					String testOwnerId = (String) infos.get(i).get("testOwnerId");
					String devOwnerId = (String) infos.get(i).get("devOwnerId");
					Date reptDate = (Date) infos.get(i).get("reptDate");
					Long bugReptVer = (Long) infos.get(i).get("bugReptVer");
					Long moduleId = (Long) infos.get(i).get("moduleId");
					
					bugBaseInfo.setModuleId(moduleId);
					bugBaseInfo.setBugReptVer(bugReptVer);
					bugBaseInfo.setTaskId(taskId);
					bugBaseInfo.setBugDesc(bugDesc);
					bugBaseInfo.setBugId(bugId);
					bugBaseInfo.setBugTypeId(bugTypeId);
					bugBaseInfo.setCurrStateId(currStateId);
					bugBaseInfo.setGeneCauseId(geneCauseId);
					bugBaseInfo.setPriId(priId);
					bugBaseInfo.setTestOwnerId(testOwnerId);
					bugBaseInfo.setDevOwnerId(devOwnerId);
					bugBaseInfo.setReptDate(reptDate);
					bugBaseInfo.setBugGradeId(bugGradeId);
					bugBaseInfo.setTestCases(null);
					
					bugBaseInfos.add(bugBaseInfo);
				}
				
				bugManagerBlh.setRelaTypeDefine(bugBaseInfos);
				bugManagerBlh.setRelaUser(bugBaseInfos);
				bugManagerBlh.setRelaTaskName(bugBaseInfos);
				bugManagerBlh.setStateName(bugBaseInfos);
			}
			pageModel.setRows(bugBaseInfos);
			pageModel.setTotal(dto.getPageModel().getTotal());
			pageModel.setPageNo(dto.getPageNo());
			pageModel.setPageSize(dto.getPageSize());
		}else{
			pageModel.setRows(null);
			pageModel.setTotal(0);
			String iterationId = dto.getIterationList().getIterationId(); //要把taskId 设置到session 中要不处理测试包里会出错，
			IterationList it = iterationService.getHibernateGenericController().findUniqueBy(IterationList.class, "iterationId", iterationId);
			if(it!=null) {
				taskIdTemp = it.getTaskId();
			}
		}
		SecurityContextHolderHelp.setCurrTaksId(taskIdTemp);
		super.writeResult(JsonUtil.toJson(pageModel));
		return super.globalAjax();
	}
	
	/** 
	* 方法名:          searchSubmitBugDetail
	* 方法功能描述:     查询关联的新提交的bug
	* @param:         
	* @return:        
	* @Author:          
	* @Create Date:   2018年8月29日 下午5:30:19
	*/
	@SuppressWarnings("unchecked")
	public View searchSubmitBugDetail(BusiRequestEvent req){
		IterationDto dto = super.getDto(IterationDto.class, req);
		if(null==dto.getPageModel()){
			dto.setPageModel(new PageModel());
		}
		
		iterationService.sumbitBugDetail(dto);
		List<BugBaseInfo> bugBaseInfos = new ArrayList<BugBaseInfo>();
		List<Map<String, Object>> infos = (List<Map<String, Object>>) dto.getPageModel().getRows();
		PageModel pageModel = new PageModel();
		String taskIdTemp = null;
		if(infos!=null){
			if(infos.size()>0){
				for (int i = 0; i < infos.size(); i++) {
					BugBaseInfo bugBaseInfo = new BugBaseInfo();
					String taskId = (String) infos.get(i).get("taskId");
					if(taskIdTemp==null) {
						taskIdTemp = taskId ; // 不要删要不后续处理测试包会有BUG 
					}
					String bugDesc = (String) infos.get(i).get("bugDesc");
					Long bugId = (Long) infos.get(i).get("bugId");
					Long bugTypeId = (Long) infos.get(i).get("bugTypeId");
					Integer currStateId = (Integer) infos.get(i).get("currStateId");
					Long bugGradeId = (Long) infos.get(i).get("bugGradeId");
					Long geneCauseId = (Long) infos.get(i).get("geneCauseId");
					Long priId = (Long) infos.get(i).get("priId");
					String testOwnerId = (String) infos.get(i).get("testOwnerId");
					String devOwnerId = (String) infos.get(i).get("devOwnerId");
					Date reptDate = (Date) infos.get(i).get("reptDate");
					Long bugReptVer = (Long) infos.get(i).get("bugReptVer");
					Long moduleId = (Long) infos.get(i).get("moduleId");
					
					bugBaseInfo.setModuleId(moduleId);
					bugBaseInfo.setBugReptVer(bugReptVer);
					bugBaseInfo.setTaskId(taskId);
					bugBaseInfo.setBugDesc(bugDesc);
					bugBaseInfo.setBugId(bugId);
					bugBaseInfo.setBugTypeId(bugTypeId);
					bugBaseInfo.setCurrStateId(currStateId);
					bugBaseInfo.setGeneCauseId(geneCauseId);
					bugBaseInfo.setPriId(priId);
					bugBaseInfo.setTestOwnerId(testOwnerId);
					bugBaseInfo.setDevOwnerId(devOwnerId);
					bugBaseInfo.setReptDate(reptDate);
					bugBaseInfo.setBugGradeId(bugGradeId);
					bugBaseInfo.setTestCases(null);
					
					bugBaseInfos.add(bugBaseInfo);
				}
				
				bugManagerBlh.setRelaTypeDefine(bugBaseInfos);
				bugManagerBlh.setRelaUser(bugBaseInfos);
				bugManagerBlh.setRelaTaskName(bugBaseInfos);
				bugManagerBlh.setStateName(bugBaseInfos);
			}
			pageModel.setRows(bugBaseInfos);
			pageModel.setTotal(dto.getPageModel().getTotal());
			pageModel.setPageNo(dto.getPageNo());
			pageModel.setPageSize(dto.getPageSize());
		}else{
			pageModel.setRows(null);
			pageModel.setTotal(0);
			String iterationId = dto.getIterationList().getIterationId(); //要把taskId 设置到session 中要不处理测试包里会出错，
			IterationList it = iterationService.getHibernateGenericController().findUniqueBy(IterationList.class, "iterationId", iterationId);
			if(it!=null) {
				taskIdTemp = it.getTaskId();
			}
		}
		SecurityContextHolderHelp.setCurrTaksId(taskIdTemp);
		super.writeResult(JsonUtil.toJson(pageModel));
		return super.globalAjax();
	}
	
	/** 
	* 方法名:          searchTestCaseDetail
	* 方法功能描述:     查询关联的测试包
	* @param:         
	* @return:        
	* @Author:          
	* @Create Date:   2018年8月29日 下午5:31:00
	*/
	@SuppressWarnings("unchecked")
	public View searchTestCaseDetail(BusiRequestEvent req){
		IterationDto dto = super.getDto(IterationDto.class, req);
		if(null==dto.getPageModel()){
			dto.setPageModel(new PageModel());
		}
		iterationService.TestCaseDetail(dto);
		List<TestCasePackage> packages = new ArrayList<TestCasePackage>();
		List<Map<String, Object>> infos = (List<Map<String, Object>>) dto.getPageModel().getRows();
		PageModel pageModel = new PageModel();
		SecurityContextHolderHelp.setCurrTaksId(dto.getTaskId());
		if(infos!=null){
			if(infos.size()>0){
				//上面dto可能为空，所以这里再加一个
				SecurityContextHolderHelp.setCurrTaksId((String) infos.get(0).get("taskId"));//增加用例包时，要用，这里要先设置上
				for (int i = 0; i < infos.size(); i++) {
					TestCasePackage testCasePackage = new TestCasePackage();
					
					String packageId = (String) infos.get(i).get("packageId");
					String taskId = (String) infos.get(i).get("taskId");
					String packageName = (String) infos.get(i).get("packageName");
					String execEnvironment = (String) infos.get(i).get("execEnvironment");
					String executor = (String) infos.get(i).get("executor");
					String remark = (String) infos.get(i).get("remark");
					Integer exeCount = (Integer) infos.get(i).get("exeCount");
					Integer notExeCount = (Integer) infos.get(i).get("notExeCount");
					
					testCasePackage.setPackageId(packageId);
					testCasePackage.setTaskId(taskId);
					testCasePackage.setPackageName(packageName);
					testCasePackage.setExecEnvironment(execEnvironment);
					testCasePackage.setExecutor(executor);
					testCasePackage.setRemark(remark);
					testCasePackage.setExeCount(exeCount);
					testCasePackage.setNotExeCount(notExeCount);

					//查询用例包的信息
					List<UserTestCasePkg>  userTestcaseL = iterationService.searchTestCasePackageInfo(packageId);
					Set<UserTestCasePkg> userSets = new HashSet<>(userTestcaseL);
					testCasePackage.setUserTestCasePkgs(userSets);
					
					packages.add(testCasePackage);
				}
				
			}
			pageModel.setRows(packages);
			pageModel.setTotal(dto.getPageModel().getTotal());
		}else{
			pageModel.setRows(null);
			pageModel.setTotal(0);
		}
		
		super.writeResult(JsonUtil.toJson(pageModel));
		return super.globalAjax();
	}
	
	/** 
	* 方法名:          searchIteraTaskDetail
	* 方法功能描述:     查询关联的任务
	* @param:         
	* @return:        
	* @Author:          
	* @Create Date:   2018年8月30日 下午2:39:02
	*/
	@SuppressWarnings("unchecked")
	public View searchIteraTaskDetail(BusiRequestEvent req){
		IterationDto dto = super.getDto(IterationDto.class, req);
		if(null==dto.getPageModel()){
			dto.setPageModel(new PageModel());
		}
		
		iterationService.TaskDetail(dto);
		List<OtherMission> OtherMissions = new ArrayList<OtherMission>();
		List<Map<String, Object>> infos = (List<Map<String, Object>>) dto.getPageModel().getRows();
		PageModel pageModel = new PageModel();
		if(infos!=null){
			if(infos.size()>0){
				for (int i = 0; i < infos.size(); i++) {
					OtherMission OtherMission = new OtherMission();
					String missionId = (String) infos.get(i).get("missionId");
					String missionName = (String) infos.get(i).get("missionName");
					String projectId = (String) infos.get(i).get("projectId");
					String chargePersonId = (String) infos.get(i).get("chargePersonId");
					String actualWorkload = (String) infos.get(i).get("actualWorkload");
					String description = (String) infos.get(i).get("description");
					String completionDegree = (String) infos.get(i).get("completionDegree");
					String status = (String) infos.get(i).get("status");
					Date realStartTime = (Date) infos.get(i).get("realStartTime");
					
					Long missionCategory = (Long) infos.get(i).get("missionCategory");
					Long emergencyDegree = (Long) infos.get(i).get("emergencyDegree");
					Long difficultyDegree = (Long) infos.get(i).get("difficultyDegree");
					String standardWorkload = (String) infos.get(i).get("standardWorkload");
					Date predictStartTime = (Date) infos.get(i).get("predictStartTime");
					Date predictEndTime = (Date) infos.get(i).get("predictEndTime");
					String createUserId = (String) infos.get(i).get("createUserId");
					Date createTime = (Date) infos.get(i).get("createTime");
					
					OtherMission.setMissionId(missionId);
					OtherMission.setProjectId(projectId);
					OtherMission.setMissionName(missionName);
					OtherMission.setChargePersonId(chargePersonId);
					OtherMission.setActualWorkload(actualWorkload);
					OtherMission.setDescription(description);
					OtherMission.setCompletionDegree(completionDegree);
					OtherMission.setStatus(status);
					OtherMission.setRealStartTime(realStartTime);
					OtherMission.setMissionCategory(missionCategory);
					OtherMission.setEmergencyDegree(emergencyDegree);
					OtherMission.setDifficultyDegree(difficultyDegree);
					OtherMission.setStandardWorkload(standardWorkload);
					OtherMission.setPredictStartTime(predictStartTime);
					OtherMission.setPredictEndTime(predictEndTime);
					OtherMission.setCreateUserId(createUserId);
					OtherMission.setCreateTime(createTime);
					
					OtherMissions.add(OtherMission);
				}
				
			}
			setMissionJoiners(OtherMissions);
			pageModel.setRows(OtherMissions);
			pageModel.setTotal(dto.getPageModel().getTotal());
		}else{
			pageModel.setRows(null);
			pageModel.setTotal(0);
		}
		
		super.writeResult(JsonUtil.toJson(pageModel));
		return super.globalAjax();
	}
	
	
	/** 
	* 方法名:          searchIteraTaskDetail
	* 方法功能描述:     查询关联的任务
	* @param:         
	* @return:        
	* @Author:          
	* @Create Date:   2018年8月30日 下午2:39:02
	*/
	@SuppressWarnings("unchecked")
	public View searchIteraInterfaceDetail(BusiRequestEvent req){
		IterationDto dto = super.getDto(IterationDto.class, req);
		if(null==dto.getPageModel()){
			dto.setPageModel(new PageModel());
		}
		
		iterationService.interfaceDetail(dto);
		List<ApiTestScene> apiTestScenes = new ArrayList<ApiTestScene>();
		List<Map<String, Object>> infos = (List<Map<String, Object>>) dto.getPageModel().getRows();
		PageModel pageModel = new PageModel();
		if(infos!=null){
			if(infos.size()>0){
				for (int i = 0; i < infos.size(); i++) {
					ApiTestScene apiTestScene = new ApiTestScene();
					
					String sceneId = (String) infos.get(i).get("sceneId");
					String taskId = (String) infos.get(i).get("taskId");
					String sceneName = (String) infos.get(i).get("sceneName");
					String executor = (String) infos.get(i).get("executor");
					String execEnvironment = (String) infos.get(i).get("execEnvironment");
					String execVersion = (String) infos.get(i).get("execVersion");
					Integer continued = (Integer) infos.get(i).get("continued");
					
					Integer execCnt = (Integer) infos.get(i).get("execCnt");
					Integer unexecCnt = (Integer) infos.get(i).get("unexecCnt");
					String creatorId = (String) infos.get(i).get("creatorId");
					String updatorId = (String) infos.get(i).get("updatorId");
					Integer executionOrder = (Integer) infos.get(i).get("executionOrder");
					
					Date planStartTime = (Date) infos.get(i).get("planStartTime");
					Date planEndTime = (Date) infos.get(i).get("planEndTime");
					Date actualStartTime = (Date) infos.get(i).get("actualStartTime");
					Date createTime = (Date) infos.get(i).get("createTime");
					Date updateTime = (Date) infos.get(i).get("updateTime");
					
					
					apiTestScene.setSceneId(sceneId);
					apiTestScene.setTaskId(taskId);
					apiTestScene.setSceneName(sceneName);
					apiTestScene.setExecutor(executor);
					apiTestScene.setExecEnvironment(execEnvironment);
					apiTestScene.setExecCnt(execCnt);
					apiTestScene.setUnexecCnt(unexecCnt);
					apiTestScene.setExecVersion(execVersion);
					
					apiTestScene.setContinued(continued);
					apiTestScene.setCreatorId(creatorId);
					apiTestScene.setCreateTime(createTime);
					apiTestScene.setUpdateTime(updateTime);
					apiTestScene.setUpdatorId(updatorId);
					apiTestScene.setExecutionOrder(executionOrder);
					apiTestScene.setPlanEndTime(planEndTime);
					apiTestScene.setPlanStartTime(planStartTime);
					apiTestScene.setActualStartTime(actualStartTime);
					
					apiTestScenes.add(apiTestScene);
				}
				
			}
			pageModel.setRows(apiTestScenes);
			pageModel.setTotal(dto.getPageModel().getTotal());
		}else{
			pageModel.setRows(null);
			pageModel.setTotal(0);
		}
		
		super.writeResult(JsonUtil.toJson(pageModel));
		return super.globalAjax();
	}
	
	/** 
	* 方法名:          deleteBugReal
	* 方法功能描述:      删除bug信息
	* @param:         
	* @return:        
	* @Author:          
	* @Create Date:   2019年2月26日 下午2:15:06
	*/
	public View deleteBugReal(BusiRequestEvent req){
		IterationDto dto = super.getDto(IterationDto.class, req);
		List<IterationBugReal> bugLists = new ArrayList<IterationBugReal>();
		if(!StringUtils.isNullOrEmpty(dto.getBugCardId())){//task关联,t_iteration_bug_real
			String[] bugCards = dto.getBugCardId().split(",");
			for (int i = 0; i < bugCards.length; i++) {
				IterationBugReal iterationBugReal = new IterationBugReal();
				iterationService.executeUpdateByHql(" delete from IterationBugReal ite where ite.bugCardId=? ", new Object[]{bugCards[i]});
				
				iterationBugReal.setBugCardId(bugCards[i]);
				iterationBugReal.setIterationId(dto.getIterationList().getIterationId());
				
				bugLists.add(iterationBugReal);
			}
			
			iterationService.fromDeletebatchSaveIterationOperHis(bugLists);
		}
		
		super.writeResult("success");
		return super.globalAjax();
	}
	
	
	/** 
	* 方法名:          deleteTaskReal
	* 方法功能描述:     删除测试包
	* @param:         
	* @return:        
	* @Author:          
	* @Create Date:   2019年2月27日 下午4:04:41
	*/
	public View deleteTestCaseReal(BusiRequestEvent req){
		IterationDto dto = super.getDto(IterationDto.class, req);
		List<IterationTestcasepackageReal> teIterationTestcasepackageReals = new ArrayList<IterationTestcasepackageReal>();
		if(!StringUtils.isNullOrEmpty(dto.getTestCaseP())){//task关联,t_iteration_task_real
			String[] testCaseP = dto.getTestCaseP().split(",");
			for (int i = 0; i < testCaseP.length; i++) {
				IterationTestcasepackageReal testcasepackageReal = new IterationTestcasepackageReal();
				iterationService.executeUpdateByHql(" delete from IterationTestcasepackageReal ite where ite.packageId=? ", new Object[]{testCaseP[i]});
				
				testcasepackageReal.setPackageId(testCaseP[i]);
				testcasepackageReal.setIterationId(dto.getIterationList().getIterationId());
				
				teIterationTestcasepackageReals.add(testcasepackageReal);
			}
			
			iterationService.fromDeletebatchSaveIterTestCaseOperHis(teIterationTestcasepackageReals);
		}
		
		super.writeResult("success");
		return super.globalAjax();
	}
	
	/** 
	* 方法名:          deleteInterfaceReal
	* 方法功能描述:     删除接口
	* @param:         
	* @return:        
	* @Author:          
	* @Create Date:   2019年2月27日 下午4:04:41
	*/
	public View deleteInterfaceReal(BusiRequestEvent req){
		IterationDto dto = super.getDto(IterationDto.class, req);
		List<IterationInterfaceReal> iterationInterfaceReals = new ArrayList<IterationInterfaceReal>();
		if(!StringUtils.isNullOrEmpty(dto.getTestCaseP())){//task关联,t_iteration_task_real
			String[] testCaseP = dto.getTestCaseP().split(",");
			for (int i = 0; i < testCaseP.length; i++) {
				IterationInterfaceReal iterationInterfaceReal = new IterationInterfaceReal();
				iterationService.executeUpdateByHql(" delete from IterationInterfaceReal ite where ite.interfaceId=? ", new Object[]{testCaseP[i]});
				
				iterationInterfaceReal.setInterfaceId(testCaseP[i]);
				iterationInterfaceReal.setIterationId(dto.getIterationList().getIterationId());
				
				iterationInterfaceReals.add(iterationInterfaceReal);
			}
			
			iterationService.fromDeletebatchSaveIterInterfaceOperHis(iterationInterfaceReals);
		}
		
		super.writeResult("success");
		return super.globalAjax();
	}
	
	
	/** 
	* 方法名:          deleteTaskReal
	* 方法功能描述:     删除项目任务
	* @param:         
	* @return:        
	* @Author:          
	* @Create Date:   2019年2月27日 下午4:04:41
	*/
	public View deleteTaskReal(BusiRequestEvent req){
		IterationDto dto = super.getDto(IterationDto.class, req);
		List<IterationTaskReal> taskReals = new ArrayList<IterationTaskReal>();
		if(!StringUtils.isNullOrEmpty(dto.getOtherMissionS())){//task关联,t_iteration_task_real
			String[] otherMissionS = dto.getOtherMissionS().split(",");
			for (int i = 0; i < otherMissionS.length; i++) {
				IterationTaskReal iterationTaskReal = new IterationTaskReal();
				iterationService.executeUpdateByHql(" delete from IterationTaskReal ite where ite.missionId=? ", new Object[]{otherMissionS[i]});
				
				iterationTaskReal.setMissionId(otherMissionS[i]);
				iterationTaskReal.setIterationId(dto.getIterationList().getIterationId());
				
				taskReals.add(iterationTaskReal);
			}
			
			iterationService.fromDeletebatchSaveIterTaskOperHis(taskReals);
		}
		
		super.writeResult("success");
		return super.globalAjax();
	}
	

	
	/** 
	* 方法名:          iterationHisRecord
	* 方法功能描述:      操作历史记录
	* @param:         
	* @return:        
	* @Author:          
	* @Create Date:   2019年2月26日 下午5:14:03
	*/
	@SuppressWarnings("unchecked")
	public View iterationHisRecord(BusiRequestEvent req){
		IterationDto dto = super.getDto(IterationDto.class, req);
		if(null==dto.getPageModel()){
			dto.setPageModel(new PageModel());
		}

		Map<String, Object> map = new HashMap<String, Object>();
		dto.setHql("from IterationOperationHistory ioh where ioh.iterationId = :iterationId order by ioh.operationTime desc");
		map.put("iterationId", dto.getIterationList().getIterationId());
		dto.setHqlParamMaps(map);
		List<IterationOperationHistory> operationHistories  = iterationService.findByHqlWithValuesMap(dto);
		PageModel pg = new PageModel();
		pg.setRows(operationHistories);
		pg.setTotal(dto.getTotal());
		super.writeResult(JsonUtil.toJson(pg));
		return super.globalAjax();
	}
	
	/** 
	* 方法名:          findAllAddBugInfo
	* 方法功能描述:      获取中间表iterationId相关的信息
	* @param:         
	* @return:        
	* @Author:          
	* @Create Date:   2019年2月28日 上午11:05:24
	*/
	@SuppressWarnings("unchecked")
	public View findAllAddBugInfo(BusiRequestEvent req){
		IterationDto dto = super.getDto(IterationDto.class, req);
		String iterMiddleTableInfoString ="";
		if ("0".equals(dto.getTestCaseP())) {//查迭代的bug中间表
			List<IterationBugReal> itReals = iterationService.findByProperties(IterationBugReal.class, new String[]{"iterationId"}, new Object[]{dto.getIterationList().getIterationId()});
			if(null!=itReals&&itReals.size()>0){
				for (int i = 0; i < itReals.size(); i++) {
					String bugId = itReals.get(i).getBugCardId();
					iterMiddleTableInfoString = bugId+" "+iterMiddleTableInfoString;
				}
			}
		}else if ("1".equals(dto.getTestCaseP())) {//查迭代的task中间表
			List<IterationTaskReal> taskReals = iterationService.findByProperties(IterationTaskReal.class, new String[]{"iterationId"}, new Object[]{dto.getIterationList().getIterationId()});
			if(null!=taskReals&&taskReals.size()>0){
				for (int i = 0; i < taskReals.size(); i++) {
					String missionId = taskReals.get(i).getMissionId();
					iterMiddleTableInfoString = missionId+" "+iterMiddleTableInfoString;
				}
			}
		}else if("3".equals(dto.getTestCaseP())){//查接口的iteration_interface中间表
			String interSql = "SELECT itr.interface_id AS interfaceId "
					+ " FROM t_iteration_list itl RIGHT JOIN t_iteration_interface_real itr "
					+ " ON itl.iteration_id = itr.iteration_id "
					+ " WHERE itl.task_id = '"+dto.getIterationList().getTaskId()+"' ";
			List<Map<String, Object>> maps = iterationService.findBySqlByJDBC(interSql.toString());
			if(null!=maps&&maps.size()>0){
				for (int i = 0; i < maps.size(); i++) {
					String interfaceId = (String) maps.get(i).get("interfaceId");
					iterMiddleTableInfoString = interfaceId+" "+iterMiddleTableInfoString;
				}
			}
		}else{//查迭代的testCase中间表
			String caseSql = "SELECT itp.package_id AS packageId "
					+ " FROM t_iteration_list itl RIGHT JOIN t_iteration_testcasepackage_real itp "
					+ " ON itl.iteration_id = itp.iteration_id "
					+ " WHERE itl.task_id = '"+dto.getIterationList().getTaskId()+"' ";
			List<Map<String, Object>> maps = iterationService.findBySqlByJDBC(caseSql.toString());
			if(null!=maps&&maps.size()>0){
				for (int i = 0; i < maps.size(); i++) {
					String packageId = (String) maps.get(i).get("packageId");
					iterMiddleTableInfoString = packageId+" "+iterMiddleTableInfoString;
				}
			}
		}
		
		super.writeResult("success^"+iterMiddleTableInfoString.trim());
		return super.globalAjax();
	}
	
	private void setMissionJoiners(List<OtherMission> otherMissions) {
		if(otherMissions==null||otherMissions.isEmpty()) {
			return;
		}
		String hql  = " from UserOtherMission uom where uom.missionId in(:ids) ";
		List<String> missionIds = new ArrayList<String>();
		if(otherMissions != null &&!otherMissions.isEmpty()) {
			for(OtherMission otherMission :otherMissions) {
				missionIds.add(otherMission.getMissionId());
			}
		}
		Map praValuesMap = new HashMap(1);
		praValuesMap.put("ids", missionIds);
		List<UserOtherMission> userOtherMissions = otherMissionService.findByHqlWithValuesMap(hql, praValuesMap, false);
		if(userOtherMissions!=null&&!userOtherMissions.isEmpty()) {
			Map<String, List<String>> missionJoinerMap = new HashMap<String, List<String>>();
			for(int i=0;i<missionIds.size();i++){
				List<String> userIds = new ArrayList<String>();
				for(int t=0;t<userOtherMissions.size();t++){
					if(missionIds.get(i).equals(userOtherMissions.get(t).getMissionId())){
						userIds.add(userOtherMissions.get(t).getUserId());
					}
				}
				missionJoinerMap.put(missionIds.get(i), userIds);
			}
			String hql1 = "select new cn.com.codes.object.User(u.id,u.name) from User u where u.id in (select uom.userId from UserOtherMission uom where uom.missionId in(:missionIds) ) ";
			Map praValuesMap1 = new HashMap(1);
			praValuesMap1.put("missionIds", missionIds);
			List<User> users = otherMissionService.findByHqlWithValuesMap(hql1, praValuesMap1, false);
			if(users != null && users.size() > 0){
				for(int y=0;y<otherMissions.size();y++){
					List<String> userIds = missionJoinerMap.get(otherMissions.get(y).getMissionId());
					List<String> userNames = new ArrayList<String>();
					for(int p=0;p<userIds.size();p++){
						for(int q=0;q<users.size();q++){
							if(userIds.get(p).equals(users.get(q).getId())){
								userNames.add(users.get(q).getName());
							}
						}
					}
					otherMissions.get(y).setMissionJoiners(listToString1(userNames,","));
				}
			}
		}
	}
	
	public static String listToString1(List<String> list, String separator) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i)).append(separator);
        }
        return list.isEmpty() ? "" : sb.toString().substring(0, sb.toString().length() - 1);
    }
	
	public View iterationBugLayout(BusiRequestEvent req)throws BaseException{
			return super.getView();
	}
	
	public View iterationTestCaseLayout(BusiRequestEvent req)throws BaseException{
		return super.getView();
	}
	
	public View iterationTaskLayout(BusiRequestEvent req)throws BaseException{
		return super.getView();
	}
	
	public View iterationInterfaceLayout(BusiRequestEvent req)throws BaseException{
		return super.getView();
	}
	
	
	/**  
	 * @return iterationService 
	 */
	public IterationService getIterationService() {
		return iterationService;
	}

	/**  
	 * @param iterationService iterationService 
	 */
	public void setIterationService(IterationService iterationService) {
		this.iterationService = iterationService;
	}

	/**  
	* @return bugManagerBlh 
	*/
	public BugManagerBlh getBugManagerBlh() {
		return bugManagerBlh;
	}

	/**  
	* @param bugManagerBlh bugManagerBlh 
	*/
	public void setBugManagerBlh(BugManagerBlh bugManagerBlh) {
		this.bugManagerBlh = bugManagerBlh;
	}

	public OtherMissionService getOtherMissionService() {
		return otherMissionService;
	}

	public void setOtherMissionService(OtherMissionService otherMissionService) {
		this.otherMissionService = otherMissionService;
	}
	
	public OutLineManagerService getOutLineService() {
		return outLineService;
	}

	public void setOutLineService(OutLineManagerService outLineService) {
		this.outLineService = outLineService;
	}

	public CaseManagerBlh getCaseManagerBlh() {
		return caseManagerBlh;
	}

	public void setCaseManagerBlh(CaseManagerBlh caseManagerBlh) {
		this.caseManagerBlh = caseManagerBlh;
	}
	
	
}
